# -*- coding: utf-8 -*-

import logging
from typing import Dict, Optional, Type, Union

from PySide6.QtCore import (
    QMetaObject,
    Qt,
)
from PySide6.QtWidgets import (
    QAbstractItemDelegate,
    QComboBox,
    QFrame,
    QHBoxLayout,
    QHeaderView,
    QLabel,
    QPushButton,
    QSizePolicy,
    QSpacerItem,
    QSpinBox,
    QTableView,
    QVBoxLayout,
    QWidget,
)

from src.models.base import IdenticalModel
from src.ui.sqlite_pagination_model import (
    PaginationSortFilterProxyModel,
    SqlitePaginationModel,
)

logger = logging.getLogger(__name__)

MAXIMUM_SECTION_SIZE = 300


class PaginationTableWidget(QWidget):
    def __init__(
        self,
        db_path: str,
        model_class: Type[IdenticalModel],
        parent=None,
        filter_fields: Optional[list[str]] = None,
    ):
        super().__init__(parent)
        self.db_path = db_path
        self.model_class = model_class
        self.setupUi(self)
        self.setup_connections()
        self.filter_fields = filter_fields or []

    def setupUi(self, page_table_widget):
        if not page_table_widget.objectName():
            page_table_widget.setObjectName("page_table_widget")
        page_table_widget.resize(800, 600)  # 增大初始尺寸

        self.verticalLayout = QVBoxLayout(page_table_widget)
        self.verticalLayout.setObjectName("verticalLayout")

        # 表格视图
        self.tableView = QTableView(page_table_widget)
        self.tableView.setObjectName("tableView")
        self.tableView.setHorizontalScrollBarPolicy(
            Qt.ScrollBarPolicy.ScrollBarAlwaysOn
        )  # 始终显示水平滚动条
        self.tableView.setSortingEnabled(True)
        # self.tableView.horizontalHeader().setStretchLastSection(True)

        self.verticalLayout.addWidget(self.tableView)

        # 分隔线
        self.line_2 = QFrame(page_table_widget)
        self.line_2.setObjectName("line_2")
        self.line_2.setFrameShape(QFrame.Shape.HLine)
        self.line_2.setFrameShadow(QFrame.Shadow.Sunken)
        self.verticalLayout.addWidget(self.line_2)

        # 分页控制区
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")

        # 左侧 spacer
        self.horizontalSpacer = QSpacerItem(
            40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum
        )
        self.horizontalLayout.addItem(self.horizontalSpacer)

        # 每页显示数量选择
        self.itemsPerPageLabel = QLabel(page_table_widget)
        self.itemsPerPageLabel.setObjectName("itemsPerPageLabel")
        self.itemsPerPageLabel.setText("每页显示:")
        self.horizontalLayout.addWidget(self.itemsPerPageLabel)

        self.itemsPerPageCombo = QComboBox(page_table_widget)
        self.itemsPerPageCombo.setObjectName("itemsPerPageCombo")
        self.itemsPerPageCombo.addItems(["50", "75", "100"])  # 可选的每页数量
        self.horizontalLayout.addWidget(self.itemsPerPageCombo)

        # 分隔符
        self.separatorLabel = QLabel(page_table_widget)
        self.separatorLabel.setObjectName("separatorLabel")
        self.separatorLabel.setText("|")
        self.horizontalLayout.addWidget(self.separatorLabel)

        # 上一页按钮
        self.prevButton = QPushButton(page_table_widget)
        self.prevButton.setObjectName("prevButton")
        self.prevButton.setText("上一页")
        self.horizontalLayout.addWidget(self.prevButton)

        # 页码输入
        self.pageSpinBox = QSpinBox(page_table_widget)
        self.pageSpinBox.setObjectName("pageSpinBox")
        self.pageSpinBox.setMinimum(1)
        self.pageSpinBox.setMaximum(1)
        self.pageSpinBox.setButtonSymbols(QSpinBox.ButtonSymbols.NoButtons)
        self.horizontalLayout.addWidget(self.pageSpinBox)

        # 总页数显示
        self.totalPagesLabel = QLabel(page_table_widget)
        self.totalPagesLabel.setObjectName("totalPagesLabel")
        self.totalPagesLabel.setText("/ 1页")
        self.horizontalLayout.addWidget(self.totalPagesLabel)

        # 下一页按钮
        self.nextButton = QPushButton(page_table_widget)
        self.nextButton.setObjectName("nextButton")
        self.nextButton.setText("下一页")
        self.horizontalLayout.addWidget(self.nextButton)

        # 右侧 spacer
        self.horizontalSpacer_2 = QSpacerItem(
            40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum
        )
        self.horizontalLayout.addItem(self.horizontalSpacer_2)

        self.verticalLayout.addLayout(self.horizontalLayout)

        QMetaObject.connectSlotsByName(page_table_widget)

    def setup_connections(self):
        """设置信号与槽连接"""
        self.prevButton.clicked.connect(self.on_prev_page)
        self.nextButton.clicked.connect(self.on_next_page)
        self.pageSpinBox.valueChanged.connect(self.on_page_changed)
        self.itemsPerPageCombo.currentTextChanged.connect(
            self.on_items_per_page_changed
        )

    def init_table_model(
        self,
        non_data_fields_dict: Optional[Dict[str, str]] = None,
        global_delegate: Optional[QAbstractItemDelegate] = None,
        delegates_dict: Optional[Dict[Union[int, str], QAbstractItemDelegate]] = None,
        section_resize_modes: Optional[Dict[int, QHeaderView.ResizeMode]] = None,
    ):
        """初始化表格模型"""
        self.source_table_model = SqlitePaginationModel(
            db_path=self.db_path,
            model_class=self.model_class,
            parent=self.tableView,
            display_non_data_fields_dict=non_data_fields_dict,
        )
        self.proxy_table_model = PaginationSortFilterProxyModel(self.tableView)
        self.proxy_table_model.setSourceModel(self.source_table_model)
        self.tableView.setModel(self.proxy_table_model)
        self.update_pagination_controls()
        if global_delegate:
            self.tableView.setItemDelegate(global_delegate)
        # 设置委托
        if delegates_dict:
            for column, delegate in delegates_dict.items():
                if isinstance(column, str):
                    column = self.proxy_table_model.get_column_index(column)
                self.tableView.setItemDelegateForColumn(column, delegate)
        self.tableView.horizontalHeader().setMaximumSectionSize(MAXIMUM_SECTION_SIZE)
        # 设置列宽调整模式
        if section_resize_modes:
            for col, mode in section_resize_modes.items():
                self.tableView.horizontalHeader().setSectionResizeMode(col, mode)
        else:
            # 自动调整初始列宽
            for col in range(self.proxy_table_model.columnCount()):
                self.tableView.horizontalHeader().setSectionResizeMode(
                    col, QHeaderView.ResizeMode.ResizeToContents
                )

        self.tableView.verticalHeader().setSectionResizeMode(
            QHeaderView.ResizeMode.ResizeToContents
        )
        self.proxy_table_model.on_sort.connect(
            lambda: self.tableView.horizontalScrollBar().setValue(0)
        )
        self.tableView.setStyleSheet("""
                QTableView::item {
                    white-space: normal;  /* 允许自动换行 */
                    padding: 2px;         /* 增加内边距，避免文本贴边 */
                }
                                     
                /* 选中单元格样式（蓝底白字） */
                QTableView::item:selected {
                    background-color: #1E88E5;  /* 深蓝色背景 */
                    color: white;  /* 白色文字 */
                    border: 1px solid #0D47A1;  /* 深色边框增强对比 */
                }
        """)

    def update_pagination_controls(self):
        """更新分页控制组件状态"""
        total_pages = self.proxy_table_model.totalPages()
        current_page = self.proxy_table_model.currentPage()

        # 更新页码输入框
        self.pageSpinBox.blockSignals(True)  # 防止触发不必要的信号
        self.pageSpinBox.setMaximum(total_pages)
        self.pageSpinBox.setValue(current_page)
        self.pageSpinBox.blockSignals(False)

        # 更新总页数显示
        self.totalPagesLabel.setText(f"/ {total_pages}页")

        # 更新按钮状态
        self.prevButton.setEnabled(current_page > 1)
        self.nextButton.setEnabled(current_page < total_pages)

        # 更新每页显示数量选择
        self.itemsPerPageCombo.blockSignals(True)
        self.itemsPerPageCombo.setCurrentText(
            str(self.proxy_table_model.itemsPerPage())
        )
        self.itemsPerPageCombo.blockSignals(False)
        self.tableView.horizontalScrollBar().setValue(0)

    def on_prev_page(self):
        """上一页"""
        if self.proxy_table_model.currentPage() > 1:
            self.proxy_table_model.loadPage(self.proxy_table_model.currentPage() - 1)
            self.update_pagination_controls()

    def on_next_page(self):
        """下一页"""
        if self.proxy_table_model.currentPage() < self.proxy_table_model.totalPages():
            self.proxy_table_model.loadPage(self.proxy_table_model.currentPage() + 1)
            self.update_pagination_controls()

    def on_page_changed(self, page_num):
        """页码改变"""
        if page_num != self.proxy_table_model.currentPage():
            self.proxy_table_model.loadPage(page_num)
            self.update_pagination_controls()

    def on_items_per_page_changed(self, text):
        """每页显示数量改变"""
        try:
            count = int(text)
            self.proxy_table_model.setItemsPerPage(count)
            self.update_pagination_controls()
        except ValueError:
            pass

    def on_refresh(self):
        """刷新"""
        self.proxy_table_model.loadPage(self.proxy_table_model.currentPage())
        self.update_pagination_controls()

    def search_id_or_name(self, search_text: str):
        """搜索"""
        self.proxy_table_model.setFilter(search_text, self.filter_fields)
        self.update_pagination_controls()
